package com.xiaofeng.pochi.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaofeng.pochi.common.Page;
import com.xiaofeng.pochi.enums.ResultEnums;
import com.xiaofeng.pochi.enums.StateEnums;
import com.xiaofeng.pochi.exception.PochiException;
import com.xiaofeng.pochi.mapper.ShopUserMapper;
import com.xiaofeng.pochi.mapper.ShopUserStatisticMapper;
import com.xiaofeng.pochi.pojo.LoginUser;
import com.xiaofeng.pochi.pojo.ShopUser;
import com.xiaofeng.pochi.pojo.ShopUserStatistic;
import com.xiaofeng.pochi.pojo.dto.ShopUserBindDto;
import com.xiaofeng.pochi.pojo.vo.ShopUserStatisticVo;
import com.xiaofeng.pochi.pojo.vo.ShopUserVo;
import com.xiaofeng.pochi.service.ShopUserService;
import com.xiaofeng.pochi.utils.IdWorker;
import com.xiaofeng.pochi.utils.ShiroUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2022/08/21/21:48
 * @Description:
 */
@Service
public class ShopUserServiceImpl extends ServiceImpl<ShopUserMapper, ShopUser> implements ShopUserService {

    @Autowired
    private ShopUserMapper shopUserMapper;

    @Autowired
    private ShopUserStatisticMapper shopUserStatisticMapper;

    @Autowired
    private IdWorker idWorker;

    @Override
    public ShopUser getByOpenId(String username) {
        return shopUserMapper.getByOpenId(username);
    }

    @Override
    public void register(ShopUser shopUser) {
        //用户入表
        long userId = idWorker.nextId();
        shopUser.setId(userId);
        shopUserMapper.save(shopUser);
        //创建用户统计对象入表
        ShopUserStatistic statistic = new ShopUserStatistic();
        long statisticId = idWorker.nextId();
        statistic.setId(statisticId);
        statistic.setUserId(userId);
        shopUserStatisticMapper.save(statistic);
    }

    @Override
    public ShopUser bindUser(ShopUserBindDto shopUserBindDto) {
        Integer bindType = shopUserBindDto.getBindType();
        if (StateEnums.NEW_USER.getCode().equals(bindType)) {
            ShopUser shopUser = shopUserMapper.getByPhone(shopUserBindDto.getPhone());
            if (shopUser != null) {
                throw new PochiException(ResultEnums.USER_REAL_EXISTS);
            }
            //获取当前用户登录信息
            LoginUser loginUser = ShiroUtils.getLoginUser();
            String openId = loginUser.getOpenId();
            shopUser = shopUserMapper.getByOpenId(openId);
            shopUser.setPassword(shopUserBindDto.getPassword());
            shopUser.setPhone(shopUserBindDto.getPhone());
            shopUserMapper.updateLoginInfo(shopUser);
            return shopUser;
        }else{
            LoginUser loginUser = ShiroUtils.getLoginUser();
            //绑定现有账户
            //查询现有的账户，更新openid
            ShopUser shopUser = shopUserMapper.getByPhone(shopUserBindDto.getPhone());
            if (shopUser == null) {
                throw new PochiException(ResultEnums.USER_NOT_FOUND);
            }
            shopUser.setOpenId(loginUser.getOpenId());
            shopUserMapper.updateLoginInfo(shopUser);
            //删除当前登录用户ID对应的账号，这个账号是没有手机号的
            shopUserMapper.clearById(loginUser.getId());
            return shopUser;
        }
    }

    @Override
    public Page<ShopUser> getByPage(Page<ShopUser> page) {
        List<ShopUser> list = shopUserMapper.getByPage(page);
        Integer count = shopUserMapper.getCountByPage(page);
        page.setList(list);
        page.setTotalCount(count);
        return page;
    }

    @Override
    public ShopUserVo get(Long id) {
        ShopUser shopUser = shopUserMapper.get(id);
        ShopUserVo vo = new ShopUserVo();
        BeanUtils.copyProperties(shopUser, vo);
        // 查询统计信息
        ShopUserStatistic statistic = shopUserStatisticMapper.getByUserId(id);
        vo.setShopUserStatistic(statistic);
        return vo;
    }

    @Override
    public void delete(Long id) {
        shopUserMapper.delete(id);
    }

    @Override
    public void enableById(Long id) {
        shopUserMapper.enableById(id);
    }

    @Override
    public void disableById(Long id) {
        shopUserMapper.disableById(id);
    }

    @Override
    public List<ShopUserStatisticVo> getTopStatistic() {
        List<ShopUserStatistic> list = shopUserStatisticMapper.getTopStatistic();
        List<Long> userIds = list.stream().map(ShopUserStatistic::getUserId).collect(Collectors.toList());
        List<ShopUser> userList = shopUserMapper.getByIds(userIds);
        List<ShopUserStatisticVo> voList = new ArrayList<>();
        for (ShopUserStatistic statistic : list) {
            ShopUser shopUser = userList.stream().filter(u -> u.getId().equals(statistic.getUserId())).findFirst().orElse(null);
            if (shopUser == null) {
                continue;
            }
            ShopUserStatisticVo consume = new ShopUserStatisticVo();
            consume.setUserName(shopUser.getNickname() + shopUser.getPhone());
            consume.setName("累计消费");
            consume.setCount(statistic.getConsumeAmount());
            voList.add(consume);

            ShopUserStatisticVo order = new ShopUserStatisticVo();
            order.setUserName(shopUser.getNickname() + shopUser.getPhone());
            order.setName("累计订单");
            order.setCount(new BigDecimal(statistic.getOrderCount()));
            voList.add(order);

            ShopUserStatisticVo coupon = new ShopUserStatisticVo();
            coupon.setUserName(shopUser.getNickname() + shopUser.getPhone());
            coupon.setName("优惠券数");
            coupon.setCount(new BigDecimal(statistic.getCouponCount()));
            voList.add(coupon);

            ShopUserStatisticVo comment = new ShopUserStatisticVo();
            comment.setUserName(shopUser.getNickname() + shopUser.getPhone());
            comment.setName("评价数");
            comment.setCount(new BigDecimal(statistic.getCommentCount()));
            voList.add(comment);

            ShopUserStatisticVo retOrder = new ShopUserStatisticVo();
            retOrder.setUserName(shopUser.getNickname() + shopUser.getPhone());
            retOrder.setName("退货数");
            retOrder.setCount(new BigDecimal(statistic.getReturnOrderCount()));
            voList.add(retOrder);

            ShopUserStatisticVo login = new ShopUserStatisticVo();
            login.setUserName(shopUser.getNickname() + shopUser.getPhone());
            login.setName("登录次数");
            login.setCount(new BigDecimal(statistic.getLoginCount()));
            voList.add(login);
        }
        return voList;
    }
}
